package com.cgtong.android.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.R;
import com.cgtong.android.bean.ProblemBean;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.widget.GlideApp;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.DownloadProgressCallBack;
import com.zhouyou.http.exception.ApiException;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;


public class ImagePreviewActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String IMAGE_INFO = "IMAGE_INFO";
    public static final String CURRENT_ITEM = "CURRENT_ITEM";
    public static final int ANIMATE_DURATION = 200;


    public static void start(Context context, List<ProblemBean.ResourceBean> urls, int curIndex) {
        Intent intent = new Intent(context, ImagePreviewActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(ImagePreviewActivity.IMAGE_INFO, (Serializable) urls);
        bundle.putInt(ImagePreviewActivity.CURRENT_ITEM, curIndex);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    private ImagePreviewAdapter adapter;
    private List<ProblemBean.ResourceBean> imgList;
    private int currentItem;
    private TextView pageIndexTxt;
    private TextView showOriginalTxt;
    private ImageView downloadOriginalTxt;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preview);
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        pageIndexTxt = (TextView) findViewById(R.id.page_txt);
        showOriginalTxt = (TextView) findViewById(R.id.show_original_txt);
        downloadOriginalTxt = (ImageView) findViewById(R.id.download_original_txt);
        showOriginalTxt.setOnClickListener(this);
        downloadOriginalTxt.setOnClickListener(this);

        //-------------------------
        Intent intent = getIntent();
        imgList = (ArrayList<ProblemBean.ResourceBean>) intent.getSerializableExtra(IMAGE_INFO);
        for (int i = 0; i < imgList.size(); i++) {
            LogUtils.d("imgList " + i + "  = " + imgList.get(i).getContent());
        }
        currentItem = intent.getIntExtra(CURRENT_ITEM, 0);
        LogUtils.d("currentItem = " + currentItem);
        //-----------------------
        String content = imgList.get(currentItem).getContent();
        String imgName = content.substring(content.lastIndexOf("/") + 1, content.length());
        File imgDir = new File(ConstantManager.ORIGINAL_PHOTO_SAVE_DIR);
        String imgPath = imgDir + "/" + imgName;
        File imgFile = new File(imgPath);
        if (imgFile.exists()) {
            showOriginalTxt.setVisibility(View.GONE);
        }

        adapter = new ImagePreviewAdapter(this, imgList);

        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(currentItem);
        viewPager.setOffscreenPageLimit(imgList.size());


        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                currentItem = position;
                pageIndexTxt.setText(String.format(getString(R.string.select), String.valueOf(currentItem + 1), String.valueOf(imgList.size())));

                String content = imgList.get(position).getContent();
                String imgName = content.substring(content.lastIndexOf("/") + 1, content.length());
                File imgDir = new File(ConstantManager.ORIGINAL_PHOTO_SAVE_DIR);
                String imgPath = imgDir + "/" + imgName;
                File imgFile = new File(imgPath);
                if (imgFile.exists()) {
                    showOriginalTxt.setVisibility(View.GONE);
                } else {
                    showOriginalTxt.setText("查看原图");
                    showOriginalTxt.setVisibility(View.VISIBLE);
                }
                LogUtils.d("onPageSelected========================= = " + imgFile.exists());

            }
        });
        pageIndexTxt.setText(String.format(getString(R.string.select), String.valueOf(currentItem + 1), String.valueOf(imgList.size())));
    }


    /**
     * 下载图片
     */
    private void showOriginalImg(final int currentItemIndex) {
        ProblemBean.ResourceBean bean = imgList.get(currentItemIndex);
        String imgUrl = bean.getContent();
        String imgName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1, imgUrl.length());
        LogUtils.d("imgName = " + imgName);

        File imgDir = new File(ConstantManager.ORIGINAL_PHOTO_SAVE_DIR);
        LogUtils.d("audioDir = " + imgDir.getAbsolutePath());
        String imgPath = imgDir + "/" + imgName;
        LogUtils.d("imgPath == " + imgPath);

        File imgFile = new File(imgPath);
        if (!imgFile.exists()) {
            EasyHttp.downLoad(imgUrl)
                    .saveName(imgName)
                    .savePath(imgDir.getAbsolutePath())
                    .execute(new DownloadProgressCallBack<String>() {
                        @Override
                        public void onStart() {
                            showOriginalTxt.setEnabled(false);
                        }

                        @Override
                        public void onError(ApiException e) {
                            ToastUtils.showShort(e.getMessage());
                        }

                        @Override
                        public void update(long bytesRead, long contentLength, boolean done) {
                            int progress = (int) (bytesRead * 100 / contentLength);
                            if (progress == 100) {
                                showOriginalTxt.setText("已完成");
                            } else {
                                showOriginalTxt.setText(String.format(getString(R.string.txt_download_original_format), progress));
                            }
                        }

                        @Override
                        public void onComplete(String path) {
                            LogUtils.d("下载现场图片成功");
                            showOriginalTxt.setEnabled(true);
                            if (currentItem == currentItemIndex) {
                                showOriginalTxt.setVisibility(View.GONE);
                            }
                            showOriginalTxt.setText("查看原图");
                            adapter.notifyDataSetChanged();
//                            if (viewPager.getChildAt(currentItemIndex) instanceof PhotoView) {
//                                PhotoView photoView = (PhotoView) viewPager.getChildAt(currentItemIndex);
//                                String content = imgList.get(currentItemIndex).getContent();
//                                String imgName = content.substring(content.lastIndexOf("/") + 1, content.length());
//                                File imgDir = new File(ConstantManager.ORIGINAL_PHOTO_SAVE_DIR);
//                                String imgPath = imgDir + "/" + imgName;
//                                File imgFile = new File(imgPath);
//                                LogUtils.d("onComplete========================= = " + imgFile.exists());
//                                if (imgFile.exists()) {
//                                    GlideApp.with(ImagePreviewActivity.this).load(imgFile)
//                                            .into(photoView);
//
//                                }
//                            }

                        }
                    });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.show_original_txt:
                showOriginalImg(currentItem);

                break;
            case R.id.download_original_txt:
                break;
        }
    }


    class ImagePreviewAdapter extends PagerAdapter implements PhotoViewAttacher.OnPhotoTapListener {

        private List<ProblemBean.ResourceBean> urls;
        private Context context;

        ImagePreviewAdapter(Context context, @NonNull List<ProblemBean.ResourceBean> urls) {
            super();
            this.urls = urls;
            this.context = context;
        }

        @Override
        public int getCount() {
            return urls.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public int getItemPosition(Object object) {
            View view = (View)object;
            int currentPage = currentItem; // Get current page index
            if(currentPage == (Integer)view.getTag()){
                return POSITION_NONE;
            }else{
                return POSITION_UNCHANGED;
            }
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_photoview, container, false);
            view.setTag(position);
            final PhotoView imageView = (PhotoView) view.findViewById(R.id.pv);

            String content = this.urls.get(position).getContent();
            String imgName = content.substring(content.lastIndexOf("/") + 1, content.length());
            File imgDir = new File(ConstantManager.ORIGINAL_PHOTO_SAVE_DIR);
            String imgPath = imgDir + "/" + imgName;
            File imgFile = new File(imgPath);
            LogUtils.d("instantiateItem==== " + imgFile.exists()+" position=== "+position);
            if (imgFile.exists()) {
                GlideApp.with(context).load(imgFile)
                        .dontAnimate()
                        .placeholder(R.drawable.icon_default_loading)
                        .error(R.drawable.icon_default_error).into(imageView);

            } else {
                String bigContent = this.urls.get(position).getBigContent();
                GlideApp.with(context).load(bigContent)
                        .dontAnimate()
                        .placeholder(R.drawable.icon_default_loading)
                        .error(R.drawable.icon_default_error).into(imageView);

            }
            imageView.setOnPhotoTapListener(this);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        /**
         * 单击屏幕关闭
         */
        @Override
        public void onPhotoTap(View view, float x, float y) {
            ((ImagePreviewActivity) context).finish();
        }


    }
}
